<template>
  <div class="all-pending-list">
    <div class="pending-list-main">
      <div class="pending-list-top"
           v-if="urlParamObj.name">
        <span>{{ urlParamObj.name }}</span>
        <span v-if="showTotal">({{ pagination.total }})</span>
      </div>
      <div :id="searchConditionContainerId"></div>
      <div class="pending-list-header">
        <CommonCounter v-if="selectedRows.length"
                       :total="pagination.total"
                       :currentSelected="selectedRows.length"
                       @cancelSelected="cancelSelected" />
        <div class="toolbar-setting">
          <CommonToolbar :allToolBtns="allToolBtns"
                         :selectedRows="selectedRows"
                         @buttonClick="buttonClick"
                         @checkOnchange="checkOnchange">
          </CommonToolbar>
        </div>
        <div class="search-part">
          <div class="search-action">
            <a-input-search :placeholder="$i18n('collaboration.new.template.search.keyWords')"
                            style="width: 272px"
                            :allowClear="true"
                            @change="onInputSearchValueChange"
                            @search="onSearch" />
          </div>
          <div class="search-condition-class">
            <SearchCondition :containerParentId="searchConditionContainerId"
                             :conditions="searchConditions"
                             @valueChange="conditionValueChange"
                             @expandChange="expandChange"></SearchCondition>
          </div>
        </div>
      </div>

      <div class="pending-list-content">
        <div>
          <AVirtuallyTable ref="avirtuallyTable"
                           :row-selection="{
              columnWidth: 60,
              ...rowSelection
            }"
                           rowKey="id"
                           :pagination="true"
                           :paginationOption="pagination"
                           :columns="columns"
                           :openVirtuallyModel="true"
                           :dataSource="dataSource"
                           size="small"
                           :bordered="false"
                           :loading="loading"
                           :localstorageKey="getLocalStorageKey"
                           :rightClickMenus="rightClickMenus"
                           @paginationChange="handleTableChange"
                           @paginationShowSizeChange="paginationShowSizeChange"
                           @contextmenuClosed="contextmenuClosed"
                           @rowClick="rowClick">
            <span slot="subject"
                  slot-scope="{ record }">
              <SubjectRender :slotData="record"
                             :urlParams="urlParamObj"
                             :hasToTop="hasToTop"
                             @toTheTop="toTheTop">
              </SubjectRender>
            </span>
            <span slot="deadLine"
                  slot-scope="{ text, record }">
              <span 
                    :title="text"
                    :class="{'color_red left flagClass text_overflow':record.dealTimeout}">
                {{ text }}
              </span>
            </span>
            <span slot="categoryLabel"
                  slot-scope="{ text, record }">
              <CategoryLabel :text="text"
                             :urlParams="urlParamObj"
                             :slotData="record"
                             :isRegistRole="isRegistRole"
                             @openLink="openLink">
              </CategoryLabel>
            </span>
            <span slot="extParam"
                  slot-scope="{ record }">
              <ExtParam :slotData="record"></ExtParam>
            </span>
            <!-- 操作 -->
            <span slot="operation"
                  slot-scope="{ record }">
              <OperationRender :slotData="record"
                               :userId="userId"
                               @editMeetingFn="editMeetingFn"
                               @cancelMeetingFn="cancelMeetingFn"
                               @attendMeeting="attendMeeting">
              </OperationRender>
            </span>
          </AVirtuallyTable>
          <TagEditModal :visible="tagModalVisible"
                        @handleModal="handleTagEditModal"
                        @callback="reloadTagData" />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  /* global axios,_ctxPath, CsrfGuard, openCtpWindow, collaborationApi, getCtpTop */
  import {getParams, loadComponentsThemeDefaultCSS, toastForward} from '../../utils';
  import CommonToolbar from '../../components/common-toolbar/index';
  import CommonCounter from '../../components/common-counter/index';
  import SearchCondition from '@/components/search-condition/index.vue';
  import AVirtuallyTable from '@/ant-virtually-table/table.vue';
  import SubjectRender from '../../components/subject-render/index.vue';
  import CategoryLabel from '../../components/category-label/index.vue';
  import ExtParam from './components/ext-param.vue';
  import OperationRender from './components/operation-render';
  import TagEditModal from '@/components/tag-edit/tag-edit-modal/index.vue';
  import collaboration from '../../utils/collaboration.js';
  import smartCodeMixin from '../../mixins/smart-code-mixin';
  import TagItem from './components/tag-item';
  import { formatRequestDataToJSON, loadExtendResource } from '@/utils/api';
  import * as Fiber from 'fiber';

  export default {
    name: 'AllPendingList',
    mixins: [smartCodeMixin],
    components: {
      CommonToolbar,
      CommonCounter,
      SearchCondition,
      AVirtuallyTable,
      SubjectRender,
      CategoryLabel,
      ExtParam,
      OperationRender,
      TagEditModal
    },
    data() {
      return {
        showTotal: false,
        allToolBtns: [],
        showCounter: false,
        searchConditionContainerId: 'search-condition-container-parent',
        dataSource: [],
        columns: [],
        selectedRowKeys: [],
        urlParamObj: {},
        pagination: {
          page: 1,
          total: 0
        },
        searchValue: '',
        selectedRows: [],
        searchConditions: [],
        loading: false,
        tagList: [],
        rightClickMenus: [],
        tagModalVisible: false,
        tagRightSelect: {}
      };
    },
    computed: {
      rowSelection() {
        return {
          selectedRowKeys: this.selectedRowKeys,
          onChange: this.onSelectChange,
          // onSelect: this.onSelectRecord,
          getCheckboxProps: (record) => ({
            props: {
              disabled: this.isDisabledCheckbox(record)
            }
          })
        };
      },
      getLocalStorageKey() {
        return this.userId + this.pageKey;
      },
      // 是否显示操作列
      showTbOperation() {
        const param = this.urlParamObj.noOperate
        return param !== '1'
      }
    },
    created() {
      this.initParams();
      this.initTableHeader();
      this.initTableData();
      window.closeAndFresh = this.reloadTableData;
      window.addEventListener('storage', this.bindStorage);
      loadComponentsThemeDefaultCSS(window._ctxPath + window._ctpSkinUrl);
    },
    mounted() {},
    methods: {
      //不需要动态更新的数据
      initParams() {
        this.pageKey;
        this.isRegistRole = false;
        this.userId = window._currentUser.id;
        this.process = {};
        this.aiSortValue = '0';
        //按钮由前端写死
        this.urlParamObj = getParams(window.location.search);
        this.urlParamObj.name
          ? (this.urlParamObj.name = window.decodeURIComponent(this.urlParamObj.name))
          : '';
        this.isTop = false;
        this.isV5Member = false;
        //当前页面没有数据是否回到第一页
        this.needReload = false;
        //高级条件
        this.seniorConditions = null;
        // 用于取消网络请求
        this.cancelToken = null;
        //新增逻辑 url里面传的模板id需要拼接搜索条件里面过滤想要的数据
        if(this.urlParamObj.templatePanel){
          var obj ={
            templatePanel:{
              templatePanel:this.urlParamObj.templatePanel
             }
          }
          this.conditionValueChange(obj,obj)
        }
      },
      reloadTableData() {
        this.needReload = true;
        this.initTableData();
        this.eventUpdateToTotolist();
      },
      reloadTagData() {
        this.initTagData();
        this.eventUpdateToTotolist();
      },
      eventUpdateToTotolist() {
        // 刷新todo菜单tag数据
        window.localStorage.setItem('updateTodoTags', Math.random());
      },
      initToolbar() {
        // this.allToolBtns = [];
        const submenu = [];
        //转发协同和转发邮件需要由插件控制
        const hasNewColl = window._hasResource('F01_newColl');
        const hasMailCreate = window._hasResource('F12_mailcreate');
        if (hasNewColl) {
          submenu.push({
            //转发协同
            id: 'transmitCol',
            name: this.$i18n('common.toolbar.transmit.col.label')
          });
        }
        if (hasMailCreate) {
          submenu.push({
            //转发邮件
            id: 'transmitMail',
            name: this.$i18n('common.toolbar.transmit.mail.label')
          });
        }

        this.allToolBtns.push({
          id: 'batchDeal',
          // name: '批处理',
          name: this.$i18n('common.batch.handle.label')
        });
        if (hasNewColl || hasMailCreate) {
          this.allToolBtns.push({
            id: 'transmit',
            name: this.$i18n('common.toolbar.transmit.label'),
            subMenu: submenu
          });
        }
        if (this.urlParamObj.from !== 'Agent')
          this.allToolBtns.push({
            id: 'autoDeal',
            name: this.$i18n('batch.autorun.label')
          });
        if (this.isHaveSmartCodePermission()) {
          // 有智码插件，并且不是vjoin平台
          this.allToolBtns.push(this.smartCodeBtnInfo);
        }
        // 初始化标签数据及按钮
        // 权限：只有从待办更多入口进来的才有标签功能，后端没有提供入口标识，暂时用pageKey作为入口标识
        if (this.urlParamObj.pageKey) this.initTagData();
      },
      initTableHeader() {
        //从栏目进来的
        if (this.urlParamObj.pageKey) {
          this.pageKey = this.urlParamObj.pageKey;
          //如果没有pageKey
        } else if (this.urlParamObj.myRemind === 'overTime') {
          this.pageKey = 'LIST_OVERDUE_PENDING';
        } else if (this.urlParamObj.from === 'Agent') {
          this.pageKey = 'LIST_AGENT';
        } else {
          this.pageKey = 'LIST_PENDING_SECTION';
        }
        const headerParams = {
          // 页面唯一标识（取值参照PageKey）
          key: this.pageKey || '',
          // 来源 0菜单 1栏目 （取值参照FromType）
          // from: 1,
          // 终端 0 pc 1 mobile （取值参照PlatformType）
          platform: 0,
          // 业务传参，由业务决定（后续可在元数据拦截器中获取到）
          arguments: {
            fragmentId: this.urlParamObj.fragmentId || '',
            ordinal: this.urlParamObj.ordinal || '',
            bigTitleIndex: this.urlParamObj.bigTitleIndex || '',
            userId: window._currentUser.id,
            from: this.urlParamObj.from || ''
          }
        };
        const url = `${_ctxPath}/rest/global/metadata/list`;
        axios.post(url, headerParams).then((data) => {
          if (data.data.code === 0) {
            const recieveData = data.data.data;
            loadExtendResource(recieveData.extra?.extendResources);
            this.hanlderHeader(recieveData);
            // this.columns = recieveData.tableColumns;
          }
        });
      },
      initTagData() {
        const _this = this;
        const params = {
          affairId: window._currentUser.id
        };
        const url = `${_ctxPath}/rest/m3/pending/getPersonalLabels?option.n_a_s=1`;
        axios.post(url, params).then((data) => {
          const tagList = data.data.data;
          this.tagList = tagList;
          const defaultRightClickMenus = [
            {
              key: 'addNewTag',
              name: this.$i18n('label.portal.new'),
              icon: 'cap-icon-jiahao',
              click() {
                _this.handleTagEditModal(true);
              }
            },
            {
              key: 'cancelTag',
              name: this.$i18n('label.cancel'),
              icon: 'cap-icon-Close',
              click(record) {
                _this.deleteTag(record.id);
              }
            }
          ];
          this.rightClickMenus = tagList.length
            ? defaultRightClickMenus.concat([{ type: 'line' }]).concat(
                tagList.map((v) => ({
                  key: v.labelId,
                  name: v.labelName,
                  height: 42,
                  customRender(h, props) {
                    let { record } = props;
                    return <TagItem onTagChange={_this.onTagChange} tagData={v} listData={record} />;
                  },
                  clickInterceptor() {
                    return true;
                  }
                }))
              )
            : defaultRightClickMenus;
          // 增加标签按钮
          const tagBtn = {
            id: 'tagBtn',
            name: tagList.length
              ? `${this.$i18n('label.mark')}...`
              : this.$i18n('label.mark.as.label'),
            type: 'tag',
            tagList: tagList,
            isVisable: true,
            reloadTableData: _this.reloadTableData,
            reloadTagData: _this.reloadTagData
          };
          if (this.allToolBtns.some((e) => e.id === 'tagBtn')) {
            this.allToolBtns = this.allToolBtns.map((v) => {
              if (v.id === 'tagBtn') {
                return tagBtn;
              } else {
                return v;
              }
            });
          } else {
            this.allToolBtns.push(tagBtn);
          }
        });
      },
      onTagChange(data) {
        const labelIds = this.tagRightSelect.labels || data.labels || [];
        const params = data.visible
          ? [...labelIds, { id: data.labelId }]
          : labelIds.filter((v) => v.id != data.labelId);
        this.tagRightSelect = {
          id: data.id,
          labels: params
        };
      },
      contextmenuClosed(record) {
        const params = this.tagRightSelect.labels || [];
        const newLabelId = params.map((v) => v.id).join(',');
        const oldLabelId = record.labels ? record.labels.map((v) => v.id).join(',') : null;
        if (
          record.id !== this.tagRightSelect.id ||
          newLabelId === oldLabelId ||
          !this.tagRightSelect.labels
        )
          return;
        if (params.length) {
          this.bantchUpdateTags([
            {
              affairId: record.id,
              app: record.applicationCategoryKey,
              labelId: newLabelId
            }
          ]);
        } else {
          this.deleteTag(record.id);
        }
        this.tagRightSelect = {};
      },
      handleTagEditModal(visible) {
        this.tagModalVisible = visible;
      },
      changeTag(affairId, app, labelId) {
        // 更新标签
        const params = {
          affairId,
          labelId,
          app
        };
        const url = `${_ctxPath}/rest/m3/pending/addLabelRelation?option.n_a_s=1`;
        axios.post(url, params).then(() => {
          this.reloadTableData();
          Fiber.message.success(this.$i18n('label.operate.success'));
        });
      },
      deleteTag(affairId) {
        // 删除标签和协同的关系
        const params = {
          affairId
        };
        const url = `${_ctxPath}/rest/m3/pending/deleteLabelRelation?option.n_a_s=1`;
        axios.post(url, params).then(() => {
          this.reloadTableData();
          Fiber.message.success(this.$i18n('label.operate.success'));
        });
      },
      bantchUpdateTags(params) {
        // 批量更新标签
        const url = `${_ctxPath}/rest/m3/pending/batchAddLabelRelation?option.n_a_s=1`;
        axios.post(url, params).then(() => {
          this.reloadTableData();
          Fiber.message.success(this.$i18n('label.operate.success'));
        });
      },
      hanlderHeader(data) {
        if (data) {
          let { tableColumns, searchConditions, globalParam } = data;
          this.searchConditions = searchConditions.filter((item) => {
            if (
              this.urlParamObj.allCount &&
              (item.extra?.type === 'sender' || item.extra?.type === 'template')
            ) {
              item.extra.allCount = this.urlParamObj.allCount;
            }
            if (item.key !== 'subject' && item.key !== 'templatePanel' ) {//新增逻辑 待办里面需要将模板搜索条件过滤掉
              return true;
            } else {
              return false;
            }
          });
          this.isV5Member = globalParam.v5Member;
          this.isRegistRole = globalParam.registRole;
          this.supportSmartCode = globalParam.supportSmartCode;
          if (this.isV5Member) {
            getCtpTop().hideLocation && getCtpTop().hideLocation();
          }
          //加入按钮
          this.initToolbar();
          this.aiSortValue = globalParam.aiSortValue;
          if (globalParam.hasAIPlugin) {
            this.allToolBtns.push({
              id: 'aiSortBtn',
              name: this.$i18n('ai.sort.labe'),
              type: 'checkbox',
              checked: this.aiSortValue === '1',
              value: '1'
            });
          }

          const customArr = ['subject', 'deadLine', 'categoryLabel', 'extParam', 'operation'];
          let tableColumnsResult = tableColumns.filter((item) => {
            delete item.extra;
            item.dataIndex = item.key;
            if (!this.showTbOperation && item.key === 'operation') {
              return false
            }
            if (customArr.includes(item.key)) {
              item.scopedSlots = { customRender: item.key };
            }
            item.dropdownMenus = {
              fieldset: true
            };
            // 操作 && 关键内容不允许排序
            if (item.key !== 'operation' && item.id !== 'extParam') {
              item.dropdownMenus.desc = true;
              item.dropdownMenus.asc = true;
            } else {
              item.fixed = 'right';
              item.width = 160;
            }
            item.customCell = (column) => {
              const fontBlod = this.isBlod(column) ? 'bold' : '';
              const customStyle = {
                'font-weight': fontBlod,
                cursor: 'pointer',
                padding: '0 8px'
              };
              if (item.key === 'subject') {
                customStyle['padding-right'] = 0;
              }
              return {
                style: customStyle
              };
            };
            if (item.key === 'workitemId') {
              return false;
            } else {
              return true;
            }
          });
          // tableColumnsResult[0].width = 1000;
          this.columns = tableColumnsResult;
        }
      },
      isBlod(slotData) {
        const { readState, subState } = slotData;
        //未读，加粗显示， 代理也要加粗
        if (
          readState === 0 ||
          subState === 11 ||
          (this.urlParamObj.from === 'Agent' && subState == 11)
        ) {
          return true;
        } else {
          return false;
        }
      },
      initTableData() {
        this.$refs.avirtuallyTable && this.$refs.avirtuallyTable.cleanSelection();
        this.loading = true;
        let sendSearch;
        let requestData = `managerMethod=getMoreList4SectionContion&arguments=`;
        const { from = '', myRemind = '', labelId = '' } = this.urlParamObj;
        if (this.seniorConditions) {
          sendSearch = this.seniorConditions;
        } else {
          const {
            propertyId = '',
            propertyFrom = '',
            fragmentId = '',
            ordinal = '',
            section = '',
            bigTitleIndex = ''
          } = this.urlParamObj;

          const initParams = {
            propertyId,
            proertyFrom: propertyFrom,
            templatePanel: '',
            senderPanel: '',
            fragmentId,
            state: '3',
            ordinal,
            sectionName: section,
            bigTitleIndex,
            isTrack: 'false',
            condition: 'subject',
            textfield: this.searchValue || '',
            aiSortValue: this.aiSortValue
          };
          sendSearch = initParams;
          this.seniorConditions = initParams;
        }
        //代理事项没有智能排序，请求的接口也不一样
        if (from === 'Agent' || myRemind === 'overTime') {
          delete sendSearch.aiSortValue;
        }
        if (from == 'Agent') {
          requestData = `managerMethod=getMoreAgentList4SectionContion&arguments=`;
        }
        if (myRemind === 'overTime') {
          sendSearch.myRemind = 'overTime';
        }
        if (from === 'All') {
          sendSearch.panel = 'all';
        }
        if (labelId) {
          sendSearch.labelId = labelId;
        }
        const pageInfo = {
          page: this.pagination.page
        };
        if (this.pagination.pageSize) {
          pageInfo.size = this.pagination.pageSize;
        }
        const sendParams = [pageInfo, sendSearch];
        const args = `${requestData}${formatRequestDataToJSON(sendParams)}`;

        if (this.cancelToken && this.cancelToken.cancel) {
          this.cancelToken.cancel();
          this.cancelToken = null;
        }
        this.cancelToken = axios.CancelToken.source();

        const url = `${_ctxPath}/ajax.do?method=ajaxAction&managerName=pendingManager&rnd=${this.getRandom()}`;
        axios.post(url, args, { cancelToken: this.cancelToken.token }).then((data) => {
          const result = data.data;
          if (result) {
            // this.pagination.total = result.total;
            if (this.needReload && this.pagination.page !== 1 && result.data.length === 0) {
              this.pagination.page = 1;
              this.needReload = false;
              this.initTableData();
              return;
            }
            this.needReload = false;
            this.dataSource = result.data;
            this.pagination.total = result.total;
            this.pagination.page = result.page;
            this.showTotal = true;
            this.loading = false;
          }
          window.parent.refreshMenuList && window.parent.refreshMenuList();
        });
      },
      expandChange() {
        this.$nextTick(() => {
          this.$refs.avirtuallyTable && this.$refs.avirtuallyTable.resizeTable();
        });
      },
      onSelectChange(selectedRowKeys, selectedRows) {
        this.selectedRowKeys = selectedRowKeys;
        this.selectedRows = selectedRows;
      },
      // onSelectRecord(record, selected, selectedRows) {
      //   this.selectedRows = selectedRows;
      // },
      onInputSearchValueChange(e) {
        this.searchValue = e.target.value;
        if (typeof this.seniorConditions.textfield !== 'undefined') {
          this.seniorConditions.textfield = this.searchValue;
        } else {
          this.seniorConditions.subject = this.searchValue;
        }
      },
      onSearch(e) {
        this.searchValue = e;
        if (typeof this.seniorConditions.textfield !== 'undefined') {
          this.seniorConditions.textfield = this.searchValue;
        } else {
          this.seniorConditions.subject = this.searchValue;
        }
        this.pagination = { ...this.pagination, page: 1 };
        this.initTableData();
      },
      cancelSelected() {
        this.showCounter = false;
        // this.selectedRows = [];
        // this.selectedRowKeys = [];
        this.$refs.avirtuallyTable && this.$refs.avirtuallyTable.cleanSelection();
      },
      //按钮点击事件
      buttonClick(buttonKey) {
        //自动处理不用选中数据
        if (buttonKey === 'autoDeal') {
          this.batchAutoRun(this.reloadTableData);
          return;
        }
        if (buttonKey === 'smartCodeScan') {
          this.showSmartCode && this.showSmartCode();
          return;
        }
        if (this.selectedRows.length < 1) {
          Fiber.message.warning(this.$i18n('ctp.dr.please.select.data.js'));
          return;
        }
        switch (buttonKey) {
          case 'batchDeal':
            this.batchHandler(this.selectedRows, this.reloadTableData);
            break;
          case 'transmitCol':
            this.transmitColFromGrid();
            break;
          case 'transmitMail':
            this.transmitMail();
            break;
        }
      },
      handleTableChange(page, pageSize) {
        this.pagination.page = page;
        this.pagination.pageSize = pageSize;
        this.initTableData();
      },
      batchHandler(chooseData, callback) {
        const _this = this;
        console.log('$.ctp.trigger', 'beforeBatchDealColl');
        const sendDevelop = $.ctp.trigger('beforeBatchDealColl', chooseData);
        if (!sendDevelop) {
          return;
        }
        // 生成ID字符串
        let dataArr = [];
        for (let i = 0; i < chooseData.length; i++) {
          const data = chooseData[i];
          let category = data.applicationCategoryKey || '1';
          if (category == 81) {
            Fiber.message.warning(this.$i18n('collaboration.template.approve.bath.noinfo'));
            return;
          }
          dataArr.push({
            affairId: data.id,
            subject: data.subject,
            category: category,
            summaryId: data.objectId
          });
        }

        // 组织参数
        let params = {};
        params.data = dataArr;
        params.callBack = (res) => {
          // this.pagination.page = 1;
          if (typeof callback === 'function') callback(res);
        };
        // 调用批量处理数据方法
        if (window.BatchProcess) {
          let process = new window.BatchProcess();
          if (typeof process.transDoBatch === 'function') {
            process.transDoBatch(params);
          }
        } else {
          throw Error('BatchProcess.transDoBatch is no');
        }
      },
      //转发协同
      async transmitColFromGrid(listFrom) {
        const selectLength = this.selectedRows.length;
        const sendData = [];
        if (selectLength > 20) {
          //只能选择20项协同进行转发
          Fiber.message.warning(this.$i18n('collaboration.grid.alert.transmitColOnly20'));
          return;
        }

        console.log('$.ctp.trigger', 'beforeTransmitCol', this.selectedRows);
        const sendDevelop = $.ctp.trigger('beforeTransmitCol', this.selectedRows);
        if (!sendDevelop) {
          return;
        }

        for (let i = 0; i < selectLength; i++) {
          const selectedObj = this.selectedRows[i];
          const app = selectedObj.applicationCategoryKey || selectedObj.app;
          if (app == 19 || app == 20 || app == 21) {
            //公文不允许转发协同
            Fiber.message.warning(this.$i18n('collaboration.grid.alert.DocumentNotForwardCol'));
            return;
          } else if (app == '32') {
            //信息报送不允许转发协同
            Fiber.message.warning(this.$i18n('collaboration.grid.alert.InfoNotForwardCol'));
            return;
          } else if (app == 81) {
            //模板审批不允许转发协同
            Fiber.message.warning(this.$i18n('collaboration.grid.alert.InfoNotTemplateApproveColl'));
            return;
          } else if (app == 4) {
            Fiber.message.warning(this.$i18n('govdoc.grid.alert.DocumentNotForwardCol'));
            return;
          } else {
            const summaryId = selectedObj.summaryId || selectedObj.objectId;
            const affairId = selectedObj.affairId || selectedObj.id;
            const isSuperNode = selectedObj.superNode;
            if (listFrom && listFrom == 'listWaitSend') {
              if (selectedObj.templeteId) {
                const templeteId = [selectedObj.templeteId];
                const result = await this.getRequestResult(
                  'colManager',
                  'isTemplateDeleted',
                  templeteId
                );

                if (result == '1') {
                  //被删除
                  Fiber.message.warning(this.$i18n('template.coll.not.ues.js', selectedObj.subject));
                  return;
                }
              }
              if (isSuperNode === true) {
                Fiber.message.warning(this.$i18n('workflow.supernode.msg.not_transmit.js'));
                return;
              }
            }
            sendData.push({
              summaryId,
              affairId
            });
          }
        }

        this.transmitColById(sendData);
      },

      getRequestResult(name, method, data) {
        const url = `${_ctxPath}/ajax.do?method=ajaxAction&managerName=${name}&rnd=${this.getRandom()}`;
        const requestData = `managerMethod=${method}&arguments=${formatRequestDataToJSON(data)}`;
        return new Promise((resolve, reject) => {
          axios
            .post(url, requestData)
            .then((data) => {
              resolve(data.data);
            })
            .catch((error) => reject(error));
        });
      },

      async transmitColById(data) {
        const _this = this;
        let checkPermissionData = '';
        let doForwardData = '';

        data.forEach((item) => {
          doForwardData += item.summaryId + '_' + item.affairId + ',';
          checkPermissionData += item.affairId + ',';
        });
        const permissionDataArr = [checkPermissionData];
        const result = await this.getRequestResult(
          'colManager',
          'checkForwardPermission',
          permissionDataArr
        );

        if (result && result instanceof Array && result.length > 0) {
          //以下协同不能转发，请重新选择
          toastForward.call(this, result);
          return;
        }

        const dialog = $.dialog({
          id: 'showForwardDialog',
          height: '400',
          width: '550',
          url: _ctxPath + '/collaboration/collaboration.do?method=showForward&data=' + doForwardData,
          title: this.$i18n('common.toolbar.transmit.col.label'),
          targetWindow: window.getCtpTop(),
          isClear: false,
          transParams: {
            commentContent: ''
          },
          buttons: [
            {
              id: 'okButton',
              text: this.$i18n('common.button.ok.label'),
              btnType: 1,
              handler: function handler() {
                dialog.getReturnValue();
              },
              OKFN: function () {
                dialog.close();
                _this.initTableData();
              }
            },
            {
              id: 'cancelButton',
              text: this.$i18n('common.button.cancel.label'),
              handler: function handler() {
                dialog.close();
              }
            }
          ]
        });
      }, //ajax判断事项是否可用。

      async transmitMail() {
        const emailShow = window._hasPlugin('webmail');
        if (emailShow) {
          //需要判断是否只勾选了一项，并给出相应的提示
          // var selectBox =grid.grid.getSelectRows();
          const selectedLength = this.selectedRows.length;
          if (selectedLength === 0) {
            //请选择要转发的协同!
            Fiber.message.warning(this.$i18n('collaboration.grid.alert.transmitCol'));
            return;
          } else if (selectedLength > 1) {
            //只能选择一项协同进行转发
            Fiber.message.warning(this.$i18n('collaboration.grid.alert.transmitColOnlyOne'));
            return;
          }
          // for(var i=0; i<selectedLength; i++){
          const selectedObj = this.selectedRows[0];
          const app = selectedObj.applicationCategoryKey || selectedObj.app;
          if (app == '19' || app == '20' || app == '21' || app == '4') {
            //公文不允许转发协同
            Fiber.message.warning(this.$i18n('collaboration.grid.alert.DocumentNotForwardEmail'));
            return;
          } else if (app == '32') {
            //信息报送不允许转发邮件
            Fiber.message.warning(this.$i18n('collaboration.grid.alert.InfoNotForwardEmail'));
            return;
          } else if (app == '81') {
            //协同模板不允许转发邮件
            Fiber.message.warning(this.$i18n('collaboration.grid.alert.InfoNotTemplateApproveEmail'));
            return;
          }
          // }

          let summaryId, affairId, isSuperNode;
          summaryId = selectedObj.summaryId || selectedObj.objectId;
          affairId = selectedObj.affairId || selectedObj.id;
          isSuperNode = selectedObj.superNode;

          const ocipParams = [{ summaryId, affairId, isSuperNode }];
          console.log('$.ctp.trigger', 'beforeTransmitMail', ocipParams);
          const sendDevelop = $.ctp.trigger('beforeTransmitMail', ocipParams);
          if (!sendDevelop) {
            return;
          }

          const summaryIdArr = [summaryId];
          const canTrans = await this.getRequestResult(
            'secretAjaxManager',
            'canTransSecretLevel',
            summaryIdArr
          );
          if (canTrans == false) {
            Fiber.message.warning(this.$i18n('collaboration.grid.alert.noTransSecretData'));
            return;
          }
          const affairIdArr = [affairId];
          const result = await this.getRequestResult(
            'colManager',
            'checkForwardPermission',
            affairIdArr
          );
          if (result && result instanceof Array && result.length > 0) {
            //以下协同不能转发，请重新选择
            toastForward.call(this, result);
            return;
          }

          if (isSuperNode === true) {
            Fiber.message.warning(this.$i18n('workflow.supernode.msg.not_transmit.js'));
            return;
          }
          //跳转门户菜单，需要确认资源
          const params = {};
          params.title = this.$i18n('common.toolbar.transmit.mail.label');
          if (window.getCtpTop() && window.getCtpTop().showMenu) {
            window
              .getCtpTop()
              .showMenu(
                _ctxPath +
                  '/collaboration/collaboration.do?method=forwordMail&summaryId=' +
                  summaryId +
                  '&affairId=' +
                  affairId,
                null,
                null,
                null,
                params
              );
          }
        }
      },
      editMeetingFn(record) {
        const needData = {
          id: record.objectId,
          state: record.meetingState,
          category: record.meetingCategory,
          createUser: record.createMemberId,
          meetingProviderCode: record.meetingProviderCode,
          link: record.link
        };
        this.editMeeting(needData, this.initTableData);
      },
      editMeeting(selected, callback) {
        const { id, state, category, createUser, meetingProviderCode, link } = selected;
        /**
         * 校验
         */

        if (createUser !== this.userId) {
          Fiber.message.warning(this.$i18n('meeting.not.theCreateor.ofMeeting.cannot.beEdit.alert'));
          return;
        }

        if (state === 60) {
          Fiber.message.warning(this.$i18n('meeting.noModification.isAllowed.for.flowAudit.alert'));
          return;
        }

        if (state !== 0 && state !== 10 && state !== 70) {
          Fiber.message.warning(
            this.$i18n('meeting.noModification.isAllowed.for.ongoing.orEnded.alert')
          );
          return;
        }
        /**
         * 周期会议支持批量编辑
         * 待发的周期会议直接编辑
         */

        const topOper = typeof isMeetingDetailPage != 'undefined' && window.isMeetingDetailPage;

        if (category === 1 && state !== 0) {
          $.messageBox({
            title: this.$i18n('common.operate.edit'),
            type: 100,
            msg: this.$i18n('mt.single.or.batch.modify') + '?',
            buttons: [
              {
                id: 'edit_single',
                text: this.$i18n('meeting.single.edit.label'),
                handler: function handler() {
                  if (topOper) {
                    location.href =
                      _ctxPath +
                      '/meeting.do?method=editor&meetingId=' +
                      id +
                      '&isBatch=false&showTab=true';
                  } else {
                    window.openWindow({
                      url:
                        _ctxPath +
                        '/meeting.do?method=editor&meetingId=' +
                        id +
                        '&isBatch=false&showTab=true'
                    });
                  }
                }
              },
              {
                id: 'edit_batch',
                text: this.$i18n('meeting.bulk.edit.label'),
                handler: function handler() {
                  if (topOper) {
                    location.href =
                      _ctxPath +
                      '/meeting.do?method=editor&meetingId=' +
                      id +
                      '&isBatch=true&showTab=true';
                  } else {
                    window.openWindow({
                      url:
                        _ctxPath +
                        '/meeting.do?method=editor&meetingId=' +
                        id +
                        '&isBatch=true&showTab=true'
                    });
                  }
                }
              }
            ]
          });
        } else {
          if (meetingProviderCode == 'personal') {
            const personalDialog = $.dialog({
              id: 'personalDialog',
              url:
                _ctxPath +
                '/apps_res/meetingintegrate/instantMeeting/html/appointmentMeeting.html?meetingId=' +
                id +
                '&r=' +
                window.getCtpTop().CsrfGuard.getUrlSurffix(),
              width: 615,
              height: 500,
              title: this.$i18n('meeting.instant.app.name'),
              buttons: [
                {
                  text: this.$i18n('common.button.ok.label'),
                  handler: function handler() {
                    const result = personalDialog.getReturnValue({
                      callBk: function callBk(params) {
                        if (params.meetingId) {
                          personalDialog.close();
                          if (callback && typeof callback == 'function') {
                            callback();
                          }
                        }
                      }
                    });

                    if (result.savePageMesage) {
                      result.savePageMesage();
                    }
                  }
                },
                {
                  text: this.$i18n('common.toolbar.cancelmt.label'),
                  handler: function handler() {
                    personalDialog.close();
                  }
                }
              ]
            });
          } else {
            if (topOper) {
              location.href =
                _ctxPath + '/meeting.do?method=editor&meetingId=' + id + '&showTab=true';
            } else {
              let url = _ctxPath + '/meeting.do?method=editor&meetingId=' + id + '&showTab=true';
              if (category === 2 && link) {
                // 高级会议直接用link地址
                url = _ctxPath + link;
              }

              window.openWindow({
                url
              });
            }
          }
        }
      },
      cancelMeetingCallback() {
        Fiber.message.success(this.$i18n('meeting.cancel.meeting.sucessful.alert'));
        this.initTableData();
      },
      cancelMeetingFn(record) {
        const needData = {
          id: record.objectId,
          state: record.meetingState,
          category: record.meetingCategory,
          createUser: record.createMemberId
        };
        this.cancelMeeting(needData, this.cancelMeetingCallback);
      },
      cancelMeeting(record, callback) {
        const _this = this;
        const { id, state, category, createUser } = record;
        /**
         * 校验
         */
        if (createUser !== _this.userId) {
          Fiber.message.warning(
            _this.$i18n('meeting.not.theCreateor.ofMeeting.cannot.beUndone.alert')
          );
          return;
        }

        if (state !== 10 && state !== 20) {
          Fiber.message.warning(_this.$i18n('meeting.has.ended.cannot.undo.alert'));
          return;
        }
        /**
         * 周期会议支持批量撤销
         */
        if (category === 1) {
          $.messageBox({
            title: _this.$i18n('common.toolbar.cancel.label'),
            type: 100,
            msg: _this.$i18n('mt.single.or.batch.cancel'),
            buttons: [
              {
                id: 'cancel_single',
                text: _this.$i18n('meeting.single.revocation.label'),
                handler: function handler() {
                  _this.openCancelDialog({
                    meetingId: id,
                    isBatch: false,
                    callback: callback
                  });
                }
              },
              {
                id: 'cancel_batch',
                text: _this.$i18n('meeting.bulk.revocation.label'),
                handler: function handler() {
                  _this.openCancelDialog({
                    meetingId: id,
                    isBatch: true,
                    callback: callback
                  });
                }
              }
            ]
          });
        } else {
          _this.openCancelDialog({
            meetingId: id,
            isBatch: false,
            callback: callback
          });
        }
      },
      /**
       * 打开会议撤销附言dialog
       * @param isBatch
       */

      openCancelDialog(opt) {
        const _this = this;
        const cancelUrl = `${_ctxPath}/ajax.do?method=ajaxAction&managerName=meetingAjaxManager&rnd=${this.getRandom()}`;

        const cancelDialog = $.dialog({
          id: 'cancelDialog',
          url:
            _ctxPath +
            '/meetingDialog.do?method=openCancelDialog' +
            window.getCtpTop().CsrfGuard.getUrlSurffix(),
          width: 450,
          height: 260,
          title: _this.$i18n('meeting.alert.cancle'),
          buttons: [
            {
              text: _this.$i18n('common.button.ok.label'),
              handler: function handler() {
                const returnVal = cancelDialog.getReturnValue();
                if(!returnVal || returnVal.error) {
                  return ;
                }
                if (returnVal.content) {
                  const sendParams = [
                    {
                      meetingId: opt.meetingId,
                      cancelComment: returnVal.content,
                      isBatch: opt.isBatch
                    }
                  ];
                  const cancelParams = `managerMethod=cancelMeeting&arguments=${JSON.stringify(
                    sendParams
                  )}`;
                  axios.post(cancelUrl, cancelParams).then((result) => {
                    if (result && result.message) {
                      Fiber.message.warning(result.message);
                    }
                    if (opt.callback && typeof opt.callback === 'function') {
                      opt.callback.apply();
                    }
                  });
                  cancelDialog.close();
                } else {
                  Fiber.message.warning(_this.$i18n('meeting.revocation.noEmpty'));
                }
              }
            },
            {
              text: _this.$i18n('common.toolbar.cancelmt.label'),
              handler: function handler() {
                cancelDialog.close();
              }
            }
          ]
        });
      },
      attendMeeting(meetingId) {
        const _this = this;
        this.process = getCtpTop().$.progressBar();
        const url = `${_ctxPath}/rest/meeting/checkIsJoinMeeting?meetingId=${meetingId}`;
        axios.get(url).then((result) => {
          if (result.data.data?.isJoinMeet) {
            const jionUrl = `${_ctxPath}/ajax.do?method=ajaxAction&managerName=meetingAjaxManager&rnd=${this.getRandom()}`;
            const joinParam = [
              {
                meetingId
              }
            ];

            const sendParams = `managerMethod=meetingView&arguments=${JSON.stringify(joinParam)}`;
            axios
              .post(jionUrl, sendParams)
              .then((viewResult) => {
                const meetingResult = viewResult.data;
                const { meetingVo, isEmcee } = meetingResult;
                this.attendMeetingFun(meetingVo, isEmcee);
              })
              .catch((err) => {
                _this.process.close();
                if (err.responseText) {
                  const msgObj = $.parseJSON(err.responseText);
                  Fiber.message.warning({
                    msg: msgObj.message
                  });
                }
              });
          } else {
            if (result.data.data?.toastDateStr) {
              Fiber.message.warning(result.data.data.toastDateStr);
            }
            _this.process.close();
          }
        });
      },

      //加入会议实现
      attendMeetingFun(meetingVo, isEmcee) {
        const _this = this;
        const pwd = meetingVo.meetingPassword;
        if (pwd) {
          $.confirm({
            msg: _this.$i18n('mt.mtMeeting.operation.btn.joinnow.confirm', pwd),
            ok_fn: function () {
              //复制密码
              if (window.clipboardData) {
                window.clipboardData.setData('Text', pwd);
              } else if (document.execCommand) {
                let toCopyPwdInput = document.createElement('input');
                toCopyPwdInput.value = pwd;
                document.body.appendChild(toCopyPwdInput);
                toCopyPwdInput.focus();
                toCopyPwdInput.select();
                document.execCommand('Copy');
                document.body.removeChild(toCopyPwdInput);
              } else {
                new window.Clipboard().copy(pwd);
              }

              Fiber.message.success({
                content: _this.$i18n('mt.mtMeeting.operation.btn.joinnow.copyPwdSuccess'),
                duration: 0.5,
                onClose() {
                  _this.joinFun(meetingVo, isEmcee);
                }
              });
            },
            cancel_fn: function () {
              _this.process.close();
            }
          });
        } else {
          _this.joinFun(meetingVo, isEmcee);
        }
      },
      joinFun(meetingVo, isEmcee) {
        const _this = this;
        const videoInfo = meetingVo.selectedVideoApps[0];
        // 适配腾讯会议
        const meetingProviderCode = meetingVo.meetingProviderCode;
        const { id: meetingId, videoMeetingId, meetingPassword: password } = meetingVo;
        if (meetingProviderCode == 'tencent') {
          // 腾讯
          const meetingUrl = `${_ctxPath}/ajax.do?method=ajaxAction&managerName=meetingAjaxManager&rnd=${this.getRandom()}`;
          const meetingParam = {
            meetingId,
            videoMeetingId,
            password,
            isEmcee
          };
          const sendParams = `managerMethod=getTencentUrl&arguments=${JSON.stringify(meetingParam)}`;
          axios
            .post(meetingUrl, sendParams)
            .then((result) => {
              _this.process.close();
              if (!result.data.success) {
                Fiber.message.warning(result.data.msg);
                return;
              }
              const data = result.data.data;
              window.openCtpWindow({
                url: data
              });
            })
            .catch((err) => {
              console.log(err);
              _this.process.close();
            });
        } else if (meetingProviderCode == 'personal') {
          _this.process.close();
          window.openCtpWindow({
            url: videoInfo.bmUrl
          });
        } else {
          // 瞩目
          if (isEmcee) {
            const isEmceeUrl = `${_ctxPath}/ajax.do?method=ajaxAction&managerName=meetingAjaxManager&rnd=${this.getRandom()}`;
            const isEmceeParam = {
              videoRoomId: videoInfo.roomId
            };
            const sendParams = `managerMethod=videoMeetingZPK&arguments=${JSON.stringify(
              isEmceeParam
            )}`;
            axios
              .post(isEmceeUrl, sendParams)
              .then((result) => {
                _this.process.close();
                if (!result.data.success) {
                  Fiber.message.warning(result.data.message);
                  return;
                }
                const data = result.data.data;
                /**
                                                                                                                                                                                     * 小T会议属于硬件会议，所有的小T会议之前zpk参数只是为了兼容原有v5前端会议模块的替换规则设置了XXXXXXXX，但是发现目前瞩目那边做了此参数的校验，导致主持人无法一键入会，
                                                                                                                                                                                     * 调整方案如下：
                                                                                                                                                                                     小 T会议根据zpk=XXXXXXXX时跳转url中不拼接此参数
                                                                                                                                                                                    */
                const zpk = 'XXXXXXXX';
                if (zpk === data[0]) {
                  window.openCtpWindow({
                    url: videoInfo.bmUrl
                  });
                } else if (data[0]) {
                  //替换掉zpk信息
                  const videoURLArr = videoInfo.bmCompereUrl.split('zpk=');
                  videoInfo.bmCompereUrl = videoURLArr[0] + 'zpk=' + data[0];

                  if (videoURLArr.length > 1) {
                    const other = videoURLArr[1].split('&');
                    if (other.length > 1) {
                      for (let i = 0; i < other.length; i++) {
                        videoInfo.bmCompereUrl += '&' + other[i];
                      }
                    }
                  }

                  window.openCtpWindow({
                    url: videoInfo.bmCompereUrl
                  });
                } else if (data[1]) {
                  Fiber.message.warning(data[1]);
                }
              })
              .catch((err) => {
                console.error(err);
                _this.process.close();
              });
          } else {
            _this.process.close();
            window.openCtpWindow({
              url: videoInfo.bmUrl
            });
          }
        }
      },
      checkOnchange(value) {
        switch (value.id) {
          case 'aiSortBtn':
            this.aiSortValue = value.checked ? '1' : '0';
            this.aiSortClick(this.aiSortValue);
            break;
        }
      },
      toTheTop(id, isTop) {
        //isTop为true时为置顶，false为取消置顶
        this.isTop = true;
        const _this = this;
        const url = `${_ctxPath}/ajax.do?method=ajaxAction&managerName=pendingManager&rnd=${this.getRandom()}`;
        const params = [
          {
            affairId: id,
            isTop: isTop
          }
        ];
        const sendParams = `managerMethod=toTheTop&arguments=${JSON.stringify(params)}`;
        axios
          .post(url, sendParams)
          .then((result) => {
            this.isTop = false;
            if (result.data === 'success') {
              if (isTop === 'true') {
                Fiber.message.success(
                  `${_this.$i18n('common.toolbar.oper.top.label')}${_this.$i18n(
                    'report.schedule.state.success'
                  )}`
                );
              } else {
                Fiber.message.success(
                  `${_this.$i18n('show.showIndex.showbar.template.unsetTop')}${_this.$i18n(
                    'report.schedule.state.success'
                  )}`
                );
              }
              this.pagination.page = 1;
              this.initTableData();
            } else {
              // if (isTop === 'true') {
              // } else {
              // Fiber.message.warning('置顶成功');
              // }
            }
          })
          .catch(() => {
            this.isTop = false;
            Fiber.message.error(_this.$i18n('cap.template.unflow.operationFailed'));
          });
      },
      paginationShowSizeChange(current, size) {
        this.pagination.page = 1;
        this.pagination.pageSize = size;
        this.initTableData();
      },
      //自动处理
      batchAutoRun(callback) {
        const _this = this;
        //弹窗地址
        const dialogUrl =
          window.getA8Top()._ctxPath + '/collaboration/batchController.do?method=batchAutoRun';
        const batchAutoRunDialog = $.dialog({
          id: 'batchAutoRunDialog',
          url: dialogUrl,
          width: 400,
          height: 180,
          title: _this.$i18n('batch.autorun.label'),
          targetWindow: window.getCtpTop(),
          transParams: {
            callbackFlush: callback
          },
          closeParam: {
            show: true,
            handler: function handler() {}
          },
          buttons: [
            {
              id: 'ok',
              text: _this.$i18n('common.button.ok.label'),
              handler: function handler() {
                const returnValue = batchAutoRunDialog.getReturnValue();

                if (returnValue && returnValue.count == 0) {
                  batchAutoRunDialog.close();
                  return;
                }

                const startProgress = getCtpTop().$.progressBar();
                const url = `${_ctxPath}/rest/app/affair/autoRun/run?option.n_a_s=1`;
                axios
                  .post(url, returnValue, {
                    headers: {
                      CSRFTOKEN: top.CSRFTOKEN || ''
                    }
                  })
                  .then((res) => {
                    // TODO: 原来有个setTimeout延迟关闭loading, 先去掉
                    // setTimeout(function () {
                    startProgress.close();
                    batchAutoRunDialog.close();
                    const result = res.data.data; //构建批处理数据对象

                    const batchObj = {
                      batchElement: result,
                      eleSize: function eleSize() {
                        return this.batchElement.length;
                      },
                      getProcessBatchData: function getProcessBatchData() {
                        const result = new window.ArrayList();

                        for (let i = 0; i < this.batchElement.length; i++) {
                          const ele = this.batchElement[i];

                          if (
                            typeof ele == 'string' ||
                            (ele &&
                              !isNaN(Number(ele.resultCode)) &&
                              parseInt(ele.resultCode, 10) < 10)
                          ) {
                            result.add(ele);
                          }
                        }

                        return result;
                      },
                      getCancelData: function getCancelData() {
                        const result = new window.ArrayList();

                        for (let i = 0; i < this.batchElement.length; i++) {
                          const ele = this.batchElement[i];

                          if (
                            ele &&
                            !isNaN(Number(ele.resultCode)) &&
                            parseInt(ele.resultCode, 10) > 10
                          ) {
                            result.add(ele);
                          }
                        }

                        return result;
                      }
                    };

                    if (batchObj.getCancelData().size() == 0) {
                      callback && callback();
                      Fiber.message.success(_this.$i18n('batch.success.tips', returnValue.count));
                      // new window.getCtpTop().CtpUiMessage({
                      //   title: this.$i18n('batch.success.tips', returnValue.count),
                      //   type: 'success'
                      // });
                      return;
                    }

                    const ur1 = _ctxPath + '/collaboration/batchController.do?method=preBatch';
                    const dialog1 = $.dialog({
                      url: ur1,
                      title: _this.$i18n('common.system.hint.label'),
                      //系统提示
                      width: 450,
                      height: 310,
                      targetWindow: window.getCtpTop(),
                      isDrag: true,
                      transParams: batchObj,
                      buttons: [
                        {
                          text: _this.$i18n('common.button.close.label'),
                          //关闭
                          handler: function handler() {
                            dialog1.close();
                            callback && callback();
                          }
                        }
                      ],
                      closeParam: {
                        show: true,
                        handler: function handler() {
                          dialog1.close();
                          callback && callback();
                        }
                      }
                    });
                    // }, 200);
                  })
                  .catch((err) => {
                    console.error(err);
                    startProgress.close();
                  });
              }
            },
            {
              id: 'cancel',
              text: _this.$i18n('common.button.cancel.label'),
              handler: function handler() {
                batchAutoRunDialog.close();
              }
            }
          ]
        }); //去掉dialog的加载动画
      },

      aiSortClick(aiSortValue) {
        this.seniorConditions.aiSortValue = aiSortValue;
        this.initTableData();

        //更新智能排序开关状态
        const params = [
          {
            spaceId: this.urlParamObj.spaceId || '',
            fragmentId: this.urlParamObj.fragmentId || '',
            ordinal: this.urlParamObj.ordinal || '',
            bigTitleIndex: this.urlParamObj.bigTitleIndex || '',
            x: this.urlParamObj.x || '',
            y: this.urlParamObj.y || '3',
            aiSortValue: aiSortValue,
            openFrom: this.urlParamObj.openFrom || '',
            source: this.urlParamObj.source || '',
            section: this.urlParamObj.uuid || ''
          }
        ];
        const url = `${_ctxPath}/ajax.do?method=ajaxAction&managerName=pendingManager&rnd=${this.getRandom()}`;

        const sendParams = `managerMethod=updateAISortValue&arguments=${JSON.stringify(params)}`;
        axios.post(url, sendParams).then((data) => {
          console.log(data);
        });
      },
      convertPortalBodyType(bodyType) {
        let bodyTypeClass = 'html_16';
        if ('FORM' === bodyType || '20' === bodyType) {
          bodyTypeClass = 'form_text_16';
        } else if ('TEXT' === bodyType || '30' === bodyType) {
          bodyTypeClass = 'txt_16';
        } else if ('OfficeWord' === bodyType || '41' === bodyType) {
          bodyTypeClass = 'doc_16';
        } else if ('OfficeExcel' === bodyType || '42' === bodyType) {
          bodyTypeClass = 'xls_16';
        } else if ('WpsWord' === bodyType || '43' === bodyType) {
          bodyTypeClass = 'wps_16';
        } else if ('WpsExcel' === bodyType || '44' === bodyType) {
          bodyTypeClass = 'xicon-wps-color xls_16';
        } else if ('Pdf' === bodyType || '45' === bodyType) {
          bodyTypeClass = 'pdf_16';
        } else if ('Ofd' === bodyType || '46' === bodyType) {
          bodyTypeClass = 'office46_16';
        } else if ('videoConf' === bodyType) {
          bodyTypeClass = 'meeting_video_16';
        }
        return bodyTypeClass;
      },
      // openLink(link, openType) {
      //   if (link.indexOf('CSRFTOKEN=') < 0) {
      //     link = link + CsrfGuard.getUrlSurffix(link);
      //   }
      //   try {
      //     //待办中心
      //     if (openType == '4') {
      //       openCtpWindow({
      //         url: _ctxPath + link
      //       });
      //     } else {
      //       parent.window.location.href(_ctxPath + link);
      //     }
      //   } catch (e) {
      //     //非IE跳转
      //     parent.window.location.href = _ctxPath + link;
      //   }
      // },
      openLink(record) {
        let { categoryLink: link, openType } = record;
        let { openFrom } = this.urlParamObj;
        if (!openFrom && this.urlParamObj.pageKey) {
          openFrom = 'pendingCenter';
        }
        if (!link) {
          // 兼容老公文，如果没有categoryLink，就取link
          link = record.link;
        }
        if (link.indexOf('CSRFTOKEN=') < 0) {
          link = link + CsrfGuard.getUrlSurffix(link);
        }
        try {
          if (openFrom == 'pendingCenter') {
            //待办中心
            if (openType == '4' || openType == '2') {
              openCtpWindow({
                url: _ctxPath + link
              });
            } else {
              parent.window.location.href(_ctxPath + link);
            }
          } else {
            window.location.href(_ctxPath + link);
          }
        } catch (e) {
          //非IE跳转
          if (openFrom == 'pendingCenter') {
            parent.window.location.href = _ctxPath + link;
          } else {
            window.location.href = _ctxPath + link;
          }
        }
      },
      rowClick(record) {
        if (this.isTop) {
          this.isTop = false;
          return;
        }
        this.openDetail(record);
      },
      async openDetail(record) {
        const {
          link,
          openType,
          id,
          applicationSubCategoryKey: app,
          applicationSubCategoryKey: subApp,
          memberId
        } = record;
        //取消加粗
        record.readState = false;
        record.subState = false;

        const result = await this.isAffairValid(id);
        if (app !== 22 && app !== 23 && !result) {
          this.initTableData();
          return;
        }
        let _url = _ctxPath + link;
        if (app === 6 && this.urlParamObj.from === 'Agent') {
          //会议查看,代理
          _url = _url + '&proxy=1&proxyId=' + memberId;
        }
        if (openType === 2) {
          this.openLink(record);
        } else {
          let isInfoPublish = false;
          if (app === 32 && subApp === 3) {
            isInfoPublish = true;
          }
          if (isInfoPublish == true) {
            window.openMagazinePublishDialog(id);
          } else {
            // this.pagination.page = 1;
            collaborationApi.showSummayDialogByURL(_url);
          }
        }
      },

      isAffairValid(affairId) {
        const _this = this;
        const url = `${_ctxPath}/ajax.do?method=ajaxAction&managerName=portalAffairManager&rnd=${this.getRandom()}`;
        const params = `managerMethod=checkAffairValid&arguments=${JSON.stringify(affairId)}`;
        return new Promise((resolve) => {
          axios.post(url, params).then((data) => {
            const msg = data.data;
            if ($.trim(msg) != '') {
              Fiber.message.warning(msg);
              resolve(false);
              return;
            }
            resolve(true);
          });
        });
      },
      bindStorage(event) {
        if (
          event.key == 'pendingDoneEvent' ||
          event.key == 'sendEvent' ||
          event.key == 'sendMeetingEvent'
        ) {
          // this.pagination.page = 1;
          this.needReload = true;
          this.initTableData();
          // 更新ToTotolist数据不一致的情况
          this.eventUpdateToTotolist();
        } else if (event.key == 'tagChange') {
          this.initTagData();
          this.initTableData();
        } else if (event.key == 'sectionTagChange') {
          // 栏目数据变化通知待办更新数据
          this.initTagData();
          this.initTableData();
          this.eventUpdateToTotolist();
        }
      },
      conditionValueChange(data, result) {
        console.log(result, 'resultresultresult');
        this.pagination.page = 1;
        const enumKeys = ['importLevel', 'subState', 'applicationEnum'];
        Object.keys(data).forEach((key) => {
          if (enumKeys.includes(key) && Array.isArray(data[key])) {
            let enumStr = '';
            data[key].forEach((enumVal) => {
              if (enumStr) {
                enumStr += ',' + enumVal;
              } else {
                enumStr += enumVal;
              }
            });
            data[key] = enumStr;
          }
        });

        const {
          propertyId = '',
          propertyFrom = '',
          fragmentId = '',
          ordinal = '',
          section = '',
          bigTitleIndex = ''
        } = this.urlParamObj;
        const {
          createDate,
          receiveDate,
          expectedProcessTime,
          subState,
          applicationEnum,
          templatePanel,
          senderPanel
        } = data;
        const seniorSearch = {
          subject: this.searchValue || '',
          importLevel: data.importLevel || '',
          sender: data.sender || '',
          createDate: createDate ? `${createDate.startDate}#${createDate.endDate}` : '',
          receiveDate: receiveDate ? `${receiveDate.startDate}#${receiveDate.endDate}` : '',
          expectedProcessTime: expectedProcessTime
            ? `${expectedProcessTime.startDate}#${expectedProcessTime.endDate}`
            : '',
          subState: subState || '',
          applicationEnum: applicationEnum || '',
          // ...result,
          propertyId,
          proertyFrom: propertyFrom,
          templatePanel: templatePanel?.templatePanel || '',
          senderPanel: senderPanel?.senderPanel || ' ',
          realSenderPanel: senderPanel?.realSenderPanel || ' ',
          fragmentId,
          state: '3',
          ordinal,
          sectionName: section,
          bigTitleIndex,
          isTrack: 'false',
          aiSortValue: this.aiSortValue,
          condition: 'comQuery'
        };
        this.seniorConditions = seniorSearch;
        this.initTableData();
      },
      // 智码扫码成功后，智码预处理时，获取解码参数
      getSmartCodeDecodeParam() {
        const obj = this.seniorSearch;
        obj.openFrom = 'morePending';
        return obj;
      },
      // 智码扫码成功后回调
      smartCodeCallBack(data) {
        collaboration.smartCodeCallBack(data);
      },
      getRandom() {
        return Math.floor(Math.random() * Math.pow(10, 5));
      },
      isShowOperation(record) {
        const showOperation =
          record.applicationCategoryKey === 6 && record.createMemberId === this.userId;
        const showEdit = !(
          record.meetingState === 60 ||
          (record.meetingState !== 0 && record.meetingState !== 10 && record.meetingState !== 70)
        );
        const showCancel = record.meetingState === 10 || record.meetingState === 20;
        const showAttend = record.showAttend;
        return {
          showOperation,
          showEdit,
          showCancel,
          showAttend
        };
      },
      isDisabledCheckbox(record) {
        const app = record.applicationCategoryKey;
        const subApp = record.applicationSubCategoryKey;
        const disabledApp = [6, 29, 8, 9, 10, 7, 26, 22, 23, 24, 32, 34, 39, 131];
        const disabledSubapp = [22, 3, 24, 32, 34];
        if (
          disabledApp.includes(app) ||
          record.thirdApp ||
          (app === 4 && disabledSubapp.includes(subApp))
        ) {
          return true;
        } else {
          return false;
        }
      }
    },
    beforeDestroy() {
      window.removeEventListener('storage', this.bindStorage);
      delete window.closeAndFresh;
    }
  };
</script>

<style>
  @import url('../../assets/css/common.css');
</style>
<style lang="scss">
  html,
  body {
    height: 100%;
    width: 100%;
    overflow: hidden;
  }
  .all-pending-list {
    position: relative;
    height: 100%;
    .pending-list-main {
      position: absolute;
      left: 0;
      right: 0;
      bottom: 0;
      top: 0;
      display: flex;
      padding-left: 16px;
      flex-direction: column;
      background-color: #ffffff;
      // background-color: #F9FAFC;
      .pending-list-top {
        padding: 12px 16px 0 0;
        font-size: 16px;
        font-weight: 600;
        color: #333333;
      }
      .pending-list-header {
        display: flex;
        padding: 12px 16px 12px 0;
        height: 56px;
        box-sizing: border-box;
      }
      .toolbar-setting {
        flex: 1;
        overflow: hidden;
      }
      .search-action {
        display: inline-block;
        width: 272px;
      }
      .search-part {
        // flex: 1;
        display: flex;
        justify-content: flex-end;
        overflow: hidden;
        margin-left: 100px;
      }

      .pending-list-content {
        flex: 1;
        padding: 0;
        position: relative;
        overflow: hidden;
        > div {
          position: absolute;
          top: 0;
          right: 0;
          bottom: 0;
          left: 0;
        }
      }
      // .tag-show {
      //   // display: inline-block;
      //   // padding: 2px 6px;
      //   border-radius: 2px;
      //   border: none;
      // }
      // .to-top-icon {
      //   position: absolute;
      //   display: none;
      //   right: 0;
      //   width: 25px;
      // }
      // .item-to-top:hover .to-top-icon {
      //   display: inline-block;
      //   cursor: pointer;
      // }
      .titleText-improtant {
        display: inline-block;
        max-width: 85%;
        max-width: calc(100% - 100px);
        overflow: hidden;
        white-space: nowrap;
        // float: left;
        text-overflow: ellipsis;
      }
      .important-level {
        // width: 32px;
        height: 18px;
        line-height: 16px;
        border-radius: 2px;
        text-align: center;
        margin-right: 2px;
        margin-left: -2px;
        font-family: PingFangSC-Semibold;
        font-weight: 600;
        display: inline-block;
        font-size: 12px;
        transform: scale(0.83);
        padding: 1px 3px;
        color: #ffffff;
        letter-spacing: 0;
        border: none;
        cursor: pointer;
        align-self: center;
      }

      .important-level-2 {
        background: #3759ec;
      }

      .important-level-3 {
        background: #ffa324;
      }

      .important-level-4 {
        background: #fc6c1d;
      }

      .important-level-5 {
        background: #fa3d12;
      }
      .opreation-style {
        display: inline-block;
        width: 56px;
        overflow: hidden;
        cursor: pointer;
        text-overflow: ellipsis;
        white-space: nowrap;
        vertical-align: middle;
      }
      .search-condition-class {
        margin-left: 12px;
        display: flex;
      }
      .margin-gap {
        margin-right: 16px;
      }
      .xls_16.xicon-wps-color{
        color: #11b5d2;
      }
    }
  }
</style>
